import { ipcMain } from 'electron'
import axios from 'axios'
import fs from 'fs'

const encrypt_cloud_host = "http://127.0.0.1:5020"
const encrypt_serves = axios.create({
  baseURL: encrypt_cloud_host,
  // timeout: 5000
})

export function setIpc4Encrypt() {
  ipcMain.handle('StringFheEncSearch', StringFheEncSearch)
  ipcMain.handle('GetPlainTextByDocId', GetPlainTextByDocId)
  ipcMain.handle('ExtractKeywords', ExtractKeywords)
  ipcMain.handle('UploadEncFile', UploadEncFile)
}

async function StringFheEncSearch(event, arg) {
  const utf8str = arg
  const res = await encrypt_serves({
    url: 'StringFheEncSearch',
    method: 'get',
    params: {
      search_str: utf8str,
    },
  })
  return res.data
}

async function GetPlainTextByDocId(event, arg) {
  const { docId, title, file_type } = arg
  const res = await encrypt_serves({
    url: 'GetPlainTextByDocId',
    method: 'get',
    params: {
      doc_id: docId,
    },
  })
  const content_base64 = res.data
  const content = Buffer.from(content_base64, 'base64')
  const os = detectOS()
  let file_path = ""
  if (os === 'Windows') {
    file_path = 'C:\\Users\\17969\\Downloads\\' + title + "." + file_type
  } else {
    file_path = '/home/huangheng/下载/' + title + "." + file_type
  }
  fs.writeFileSync(file_path, content)
  return { content: content.toString(), file_path }
}

function detectOS() {
  const platform = process.platform;

  if (platform === 'win32') {
    return 'Windows';
  } else if (platform === 'linux') {
    return 'Linux';
  } else if (platform === 'darwin') {
    return 'macOS';
  } else {
    return 'Other OS';
  }
}

async function ExtractKeywords(event, args) {
  const { content, } = args
  const res = await encrypt_serves({
    url: 'ExtractKeywords',
    method: 'post',
    data: {
      content,
    }
  })
  return res.data
}

async function UploadEncFile(event, args) {
  const { content_base64, file_type, title, terms } = args
  const res = await encrypt_serves({
    url: 'UploadEncFile',
    method: 'post',
    data: {
      content_base64,
      title,
      file_type,
      keywords: terms,
    },
  })
  return res.data
}